<?php
/**
 * 费用审批控制器
 * Created by PhpStorm.
 * User:孙凯
 * Date: 2018-06-05
 * Time: 12:52
 */

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Support\Facades\DB;

class FeeController extends Controller
{

    /**
     * 【司机费用审批列表】
     * @Author sk
     * @DateTime 2018-06-05
     * @param Request $request
     * @return array
     */
    public function index(Request $request)
    {
        $array = $request->all();
        if (empty($num)) {
            $num = 0;
        } else {
            $num = $array['number'];
        }
        $select = [
            'chauffeur_fee_check.type',//1费用类型
            'chauffeur_fee_check.fee_number',//1费用金额
            'chauffeur_fee_check.apply_time',//1申请时间
            'chauffeur_fee_check.chauffeur_id',//司机id
            'chauffeur_fee_check.remark',//1备注
            // 'chauffeur_fee_check.status',//'状态:1:通过,2:拒绝,3:审核中）',
            'chauffeur_fee_check.number',//1工单号
            'chauffeur_fee_check.reviewer',//审核人
            'chauffeur_fee_check.reason',//审核原因
            'chauffeur_fee_check.time',//审核时间
            'driver.driver_name',//1司机姓名
            //  'driver.convoy_id',
            'convoy.name',//1车队名称
            // 'convoy.branch_id',
            'branch.company_name'//1机构名称
        ];
        $starttime = strtotime($request['starttime']);
        $endtime = strtotime($request['endtime']);
        if (isset($request['starttime']) || isset($request['endtime'])) {
            $handle = DB::table('chauffeur_fee_check')
                ->join('driver', 'chauffeur_fee_check.chauffeur_id', '=', 'driver.id')//差司机
                ->join('convoy', 'driver.convoy_id', '=', 'convoy.id')//车队
                ->leftJoin('branch', 'convoy.branch_id', '=', 'branch.id')//机构
                ->whereBetween('chauffeur_fee_check.save_time', [$starttime, $endtime])
                ->select($select)
                ->orderBy('chauffeur_fee_check.apply_time', 'desc');
        } else {
            $handle = DB::table('chauffeur_fee_check')
                ->join('driver', 'chauffeur_fee_check.chauffeur_id', '=', 'driver.id')//差司机
                ->join('convoy', 'driver.convoy_id', '=', 'convoy.id')//车队1
                ->join('branch', 'convoy.branch_id', '=', 'branch.id')//机构
                ->select($select)
                ->orderBy('chauffeur_fee_check.apply_time', 'desc');
        }
        /*foreach ($array as $key => $val) {
            dd( $array );
            $array[$key] && $handle->where($key, 'like', '%' . $val . '%');
        }*/
        $datas = $handle->get();
        $data = json_decode(json_encode($datas), true);
        foreach ($data as $k => &$v) {

            $v['time'] = date('Y-m-d H:i:s', $v['time']);
            $v['apply_time'] = date('Y-m-d H:i:s', $v['apply_time']);
        }
        return response(['mag' => $data, 'code' => 1000, 'message' => '司机费用审批列表数据返回成功！'], 200);

    }

    /**
     * 【司机费用审批详情show】
     * @param number int 申请工单号
     * @param chauffeur_id int 司机id
     * @param type int 1:通过申请，2:拒绝申请
     * @Author sk
     * @DateTime 2018-06-05
     * @param Request $request
     * @return array
     */
    public function show(Request $request)
    {
        $array = $request->all();
        $number = $array['number'];
        try {
            if (empty($array['chauffeur_id']) || empty($array['number'])) {
                return '参数不完整';
            }
            $id = $array['chauffeur_id'];
            //查询司机的信息
            $info = Db::table('driver')->where('id', $id)->first();
            //查询车队的信息
            //查询的字段
            $convoydata = [
                'name',//车队名称
                'branch_id',//机构的id
                'captain_id',//队长的id
            ];

            $convoy = Db::table('convoy')->where('id', $info->convoy_id)->select($convoydata)->first();

            //查询队长姓名
            $captainname = Db::table('driver')->where('id', $convoy->captain_id)->select('driver_name')->first();
            $captainname = get_object_vars($captainname);
//dd($captainname);
            //查询机构的信息
            $branch = Db::table('branch')->where('id', $convoy->branch_id)->select('company_name')->first();
            $branch = get_object_vars($branch);
            // dd($branch);
            //查询司机的申请内容
            #字段
            $check = [
                'fee_voucher',//费用凭证
                'remark',//备注
                'fee_number'//费用报销金额
            ];
            $obj = DB::table('chauffeur_fee_check')->where('id', $id)->first();
            if (empty($obj)){
                return '无数据';
            }
           //  dd($obj);
            //审核日志查询
           // $vav = DB::table('approval')->select('approval_id')->get();
            $appol = Db::table('approval_log')->whereIn('role_id', [1, 2, 3,4,5,6,7,8,9])->where('number', $number)->get();
            $a = json_decode(json_encode($appol), true);
//dd($a);
            foreach ($a as $k => &$v) {
                $v['time'] = date('Y-m-d H:i:s', $v['time']);
                $data['role_id']  = $v['role_id'];
                $dd = $v['lead'];
                $tt = $v['time'];
            }
            //dd($cc);
            //$cc= $data['role_id'] ;
            $data['lead'] = $dd;
            $info = get_object_vars($info);
           // $ob = DB::table('roles')->where('id',$cc)->get();
            foreach ($a as $k => &$val) {
                // $info= get_object_vars($info);
                switch ($val['results']) {
                    case 0:
                        $pass[$k]['title'] = '创建';
                        $pass[$k]['name'] = $info['driver_name'];
                        $pass[$k]['results']=$val['results'];
                        $pass[$k]['time'] = $tt;
                        break;
                    case 1:
                        $pass[$k]['title'] = '车队管理员审批';
                        $pass[$k]['name'] = $dd;
                        $pass[$k]['results']=$val['results'];
                        $pass[$k]['time'] = $tt;
                        break;
                    case 2:
                        $pass[$k]['title'] = '财务管理员审批';
                        $pass[$k]['name'] = $dd;
                        $pass[$k]['results']=$val['results'];
                        $pass[$k]['time'] = $tt;
                        break;
                    case 4:
                        $pass[$k]['title'] = '完成';
                        $pass[$k]['results']=$val['results'];
                        $pass[$k]['time'] = $tt;
                        break;
                }
            }
            $obj = get_object_vars($obj);
            $convoy = get_object_vars($convoy);
            $data['time'] = date('Y-m-d H:i:s', $obj['time']);//申请发起时间
            $data['type'] = $obj['type'];//费用类型
            $data['from'] = $obj['from'] = 1 ? '司机' : 'APP';//申请来源:1:司机,2:APP

            $data['fee_voucher'] = $obj['fee_voucher'];//费用凭证
            $data['remark'] = $obj['remark'];//备注
            $data['fee_number'] = $obj['fee_number'];//费用报销金额
            $data['name'] = $convoy['name'];//车队名称
            $data['driver_name'] = $captainname['driver_name'];//队长名称
            $data['company_name'] = $branch['company_name'];//机构名称
            $data = json_decode(json_encode($data));
            /* $pass['time'] = date('Y-m-d H:i:s', $obj['time']);//申请发起时间

             $pass['name'] = $info['driver_name'];*/
            return $a ? response(['data' => $a, 'a' => $data, 'pass' => $pass, 'code' => 1000, 'message' => '信息返回成功！'], 200) : response(['data' => '', 'code' => 1011, 'message' => '信息返回失败！'], 400);

        } catch (JWTException $e) {
            return response(['msg' => '', 'code' => 1011, 'message' => '非法的token']);
        }

    }

    /**
     * 【司机费用审批详情save】
     * @Author sk
     * @DateTime 2018-06-05
     * @param type 1 tonguo
     * @param Request $request
     * @return array
     */
    public function save(Request $request)
    {
        $data = $request->all();
        if (empty($data['chauffeur_id']) || empty($data['number'])) {
            return '请确认填写参数是否完整';
        }
        $id = $data['chauffeur_id'];
        $number = $data['number'];//申请工单号码
        try {
            $ss = DB::table('chauffeur_fee_check')->where([
                ['status', '<>', '3'],
                ['number', '=', $number],
                ['id', '=', $id]
            ])->first();
            $ss = json_decode(json_encode($ss), true);
            if (isset($ss)) {
                return response(['msg' => $ss, 'code' => 1000, 'message' => '同一级已经审批！'], 200);
            } else {
                $status = DB::table('chauffeur_fee_check')->where('id', $id)->first();
                $status = get_object_vars($status);
                #type 1 通过
                if ($data['type'] == 1) {
                    if ($status['status'] == 1) {
                        return response(['msg' => $status, 'code' => 1000, 'message' => '您审批通过成功！'], 200);
                    } else {
                        if (empty($data['role_id'] || empty($data['lead'])) || $data['opinion']) {
                            return '请确认填写的数据是否完整';
                        } else {
                            $data['lead'] = $data['lead'] = 1 ? '系统' : $data['lead'];
                            $sg = Db:: table('approval_log')->where('number', $data['number'])
                                ->insert([
                                    'role_id' => $data['role_id'],
                                    'lead' => $data['lead'],
                                    'time' => time(),
                                    'results' => 1,
                                    'opinion' => $data['opinion'],
                                    'number' => $data['number'],
                                    'circuit_number' => date('his') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT),
                                ]);
                            $msg = json_decode(json_encode($sg), true);
                            $save = DB::table('chauffeur_fee_check')->where('id', $id)->update(['status' => 1]);
                            $save = json_decode(json_encode($save), true);
                            return $save && $msg ? response(['msg' => $save, 'mes1' => $msg, 'code' => 1000, 'message' => '审批通过成功！'], 200) : response(['msg' => '', 'code' => 1011, 'message' => '审批通过失败！'], 400);
                        }
                    }
                } elseif ($data['type'] == 2) {
                    //type 2 拒绝
                    if ($status['status'] == 2) {
                        return response(['msg' => $status, 'code' => 1000, 'message' => '审批拒绝成功！'], 200);
                    } else {
                        $sg = Db:: table('approval_log')->where('number', $data['number'])
                            ->insert([
                                'role_id' => $data['role_id'],
                                'lead' => $data['lead'],
                                'time' => time(),
                                'results' => 2,
                                'opinion' => $data['opinion'],
                                'number' => $data['number'],
                                'circuit_number' => date('his') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT),
                            ]);
                        $msg = json_decode(json_encode($sg), true);
                        $deny = DB::table('chauffeur_fee_check')->where('id', $id)->update(['status' => 2]);
                        $deny = json_decode(json_encode($deny), true);
                        return $deny && $msg ? response(['msg' => $deny, 'mes1' => $msg, 'code' => 1000, 'message' => '审批拒绝成功！'], 200) : response(['msg' => '', 'code' => 1011, 'message' => '审批拒绝失败！'], 400);
                    }
                }
            }
        } catch (JWTException $e) {
            return response(['msg' => '', 'code' => 1011, 'message' => '验证不通过']);
        }
    }

    /**
     * 【司机费用审批同级别审批之后不在审批提醒】
     * @param number int 申请工单号
     * @param chauffeur_id int 司机id
     * @Author sk
     * @DateTime 2018-06-07
     * @param Request $request
     * @return array
     */
    public function rank(Request $request)
    {
        $array = $request->all();
        try {
            //$arr = (JWTAuth::parseToken()->authenticate());
            // $data = json_decode($data, true);
            $id = $array['chauffeur_id'];
            $number = $array['number'];
            /* $status = DB::table('approval_log')->where('number', $number)->first();
            $status = get_object_vars($status);
            DB::table('roles')->where('id', $status['approval_id'])->get();*/
            //查询审批状态 status！==3

            $status = DB::table('chauffeur_fee_check')->where([
                ['status', '<>', '3'],
                ['number', '=', $number],
                ['id', '=', $id]
            ])->first();
            return $status ? response(['msg' => $status, 'code' => 1000, 'message' => '同一级已经审批！'], 200) : '';
        } catch (JWTException $e) {
            return response(['msg' => '', 'code' => 1011, 'message' => '验证不通过']);
        }

    }

    /***
     * 司机查询根据条件
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function showindex(Request $request)
    {
        $keys = $request->all();
        $handle = DB::table('driver');
        foreach ($keys as $key => $val) {
            $keys[$key] && $handle->where($key, 'like', '%' . $val . '%');
        }
        $datas = $handle->get()->toarray();
        $data = json_encode($datas);
        return response(['mag' => $data, 'code' => 1000, 'message' => '数据返回成功！'], 200);
    }

    /**
     * 【费用类型添加】
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|string|\Symfony\Component\HttpFoundation\Response
     */
    public function add(Request $request)
    {
        $data = $request->get('type');
        // $data = array_splice($dat, 1);
        //dd($data);
        if (empty($data)) {
            return '请确认填写参数是否完整';
        }
        $data2['type'] = $data;
        $msg = DB::table('fee_type')->insert($data2);
        $msg = json_decode(json_encode($msg), true);
        return $msg ? response(['msg' => $msg, 'message' => '添加成功', 'code' => '1000'], 200) : response(['msg' => '', 'message' => '添加失败', 'code' => '1011'], 400);
    }

    /**
     * 【费用类型删除】
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|string|\Symfony\Component\HttpFoundation\Response
     */
    public function del(Request $request)
    {
        $data = $request->all();
        //  dd($data);
        if (empty($data['id'])) {
            return '请确认填写参数是否完整';
        }
        $msg = DB::table('fee_type')->where('id', $data['id'])->delete();
        $msg = json_decode(json_encode($msg), true);
        return $msg ? response(['msg' => $msg, 'message' => '操作成功', 'code' => '1000'], 200) : response(['msg' => '', 'message' => '操作失败', 'code' => '1011'], 400);
    }

    /**
     * 【费用类型展示】
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function see()
    {
        $data = DB::table('fee_type')->get()->toarray();
        $msg = json_decode(json_encode($data), true);
        return $msg ? response(['msg' => $msg, 'message' => '请求成功', 'code' => '1000'], 200) : response(['msg' => '', 'message' => '请求失败', 'code' => '1011'], 400);
    }

    public function create(Request $request)
    {
        $dat = $request->all();
        $data = array_splice($dat, 0);
        $id = $data['chauffeur_id'];
        $num = $data['number'];
        $chuf = DB::table('chauffeur_fee_check')->where('id', $num)->first();//时间
        //  dd($chuf);
        $name = DB::table('driver')->where('id', $id)->first();//司机姓名
        dd($name);
        $spl = DB::table('approval_log')->where('number', $num)->first();//审批流id；谁审批过了
        $ss = DB::table('approval')->where('approval_id', $spl['approval_id'])
            ->first();//角色姓名reset_person
    }
}
